<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>单个文件上传</title>
    </head>
    <body>
        <!-- 方法必须为POST -->
        <form class="" action="demo.php" method="post" enctype="multipart/form-data">
            Username: <input type="text" name="username" value=""><br>
            Upload: <input type="file" name="upfile" value=""><br>
            <input type="submit" name="submit" value="提交">
        </form>
    </body>
</html>

<?php
/**
 * Array (
 *         [username] => 11111
 *       [submit] => 提交
 * )
 *  Array (
 *      [upfile] => Array (
 *          [name] => Penguin.tif
 *           [type] => image/tiff
 *            [tmp_name] => /Applications/MAMP/tmp/php/phpD8NvF9
 *             [error] => 0
 *          [size] => 229750
 *      )
 *  )
 *
 */
if(isset($_POST['submit'])) {

    // 将临时目录下的上传的文件，复制到我指定的目录下，指定的名字就可以完成上传

    $error = $_FILES['upfile']['error'];
    //第一步：检查错误
    if($error > 0) {
        switch ($error) {
            case '1':
                echo "上传文件的大小超出了约定值";
                break;
            case '2':
                echo "上传文件大小超出了HTML表单隐藏域属性的MAX_FILE_SIZE元素所指定的最大值";
                break;
            case '3':
                echo "文件只被部分上传";
                break;
            case '4':
                echo "没有上传任何文件";
                break;
            case '6':
                echo "找不到临时文件夹";
                break;
            case '7':
                echo "文件写入失败";
                break;

            default:
                echo "not found error";
                break;
        }
    }
    //第二步：判断类型
    if(($_FILES["upfile"]["type"] == "image/gif")
        || ($_FILES["upfile"]["type"] == "image/jpeg")
        || ($_FILES["upfile"]["type"] == "image/png")
    ) {
            echo "文件类型正确";
    } else {
        echo "文件类型非法";
        exit;
    }

    // 第三步：判断大小
    $maxsize = 800000;
    if(!($_FILES["upfile"]["size"] < $maxsize)){
        echo "文件超过了".$maxsize;
        exit;
    }

    // 第四步：随机文件名
    $name_arr = explode('.', basename($_FILES['upfile']['name']));
    $extendname = ".".array_pop($name_arr);

    $tmpfile = $_FILES['upfile']['tmp_name'];
    // $srcname = "./upload/".$_FILES['upfile']['name'];
    $srcname = "./upload/".date(YmDHis).rand(100, 999).$extendname;

    if(move_uploaded_file($tmpfile, $srcname)) {
        echo "Success!";
    } else {
        echo "Failed";
    }
}
